
// setDomain("127.0.0.1:8001")
outputLog('APP 进入测试 070106')


// document.getElementById('main_iframe').style.display = 'none !important'
// document.getElementById('test-btn-block').style.display = 'block !important'

// alert('APP 进入测试 062203')
function outputLog(msg,msg2){
     console.log(msg)
    // alert(msg)
}

var successCallback = function (result) {
    // outputLog('成功：'+result)
};
var errorCallback = function (error) {
    outputLog('错误：'+error)
};



function getCode(unit){
    if(unit == null) return null
    switch(unit){
        // case 'm³': return '1C2E1B74026DFC0a1C261B7400';
        // case '㎡': return '1C2E1B74026DFd1C261B7400';
        case 'm³': return 'm3';
        case '㎡': return 'm2';
        case 'm²': return 'm2';
        
        default: return unit;
    }
}
// 立方：1C2E1B7402FC1C261B74000a 平方：1C2E1B74026DFd1C261B7400



function connectPrinter() {
    //连接打印机
    try {
        JXPrintPlugin.connectPrinter(successCallback, errorCallback);
    } catch (error) {
        outputLog("Error: " + error)
    }
}
function closeConnect() {
    //断开连接
    try {
        JXPrintPlugin.closeConnect(successCallback, errorCallback);
    } catch (error) {
        outputLog("Error: " + error)
    }
}
function setPaperType() {
    //设置纸类型
    try {
        var jsonstr = [0];
        JXPrintPlugin.setPaperType(jsonstr, successCallback, errorCallback);
    } catch (error) {
        outputLog("Error: " + error)
    }
}
function setDensity() {
    //设置浓度
    try {
        var jsonstr = [2];
        JXPrintPlugin.setDensity(jsonstr, successCallback, errorCallback);
    } catch (error) {
        outputLog("Error: " + error)
    }
}
function setPaperFeed() {
    //走纸
    try {
        var jsonstr = [5];
        JXPrintPlugin.setPaperFeed(jsonstr, successCallback, errorCallback);
    } catch (error) {
        outputLog("Error: " + error)
    }
}
function setPaperBack() {
    //退纸
    try {
        var jsonstr = [1];
        JXPrintPlugin.setPaperBack(jsonstr, successCallback, errorCallback);
    } catch (error) {
        outputLog("Error: " + error)
    }
}
function printSelfCheck() {
    //打印自检页
    try {
        JXPrintPlugin.printSelfCheck(successCallback, errorCallback);
    } catch (error) {
        outputLog("Error: " + error)
    }
}
function printText() {
    //打印文本
    try {
        var jsonstr = ["打印文本演示\n"];
        JXPrintPlugin.printText(jsonstr, successCallback, errorCallback);
    } catch (error) {
        outputLog("Error: " + error)
    }
}
function printBarCode() {
    //打印条码
    try {
        var jsonstr = [9, 0, 76, 6, "abc123"];
        JXPrintPlugin.printBarCode(jsonstr, successCallback, errorCallback);
    } catch (error) {
        outputLog("Error: " + error)
    }
}
function printImage() {
    //打印图片
    try {
        var jsonstr = ["img.jpg", 3, 0, false];
        JXPrintPlugin.printImage(jsonstr, successCallback, errorCallback);
    } catch (error) {
        outputLog("Error: " + error)
    }
}
function printTable() {
    //打印表格
    try {
        //创建表格
        var tableTitle = ["品名;数量;单价;金额",";","14,6,6,6"];
        JXPrintPlugin.createTable(tableTitle, null, errorCallback);
        //添加行
        var tableRow1 = ["保鲜袋;10.00;1;10.00"];
        var tableRow2 = ["铁丝挂钩;5.00;2;10.00"];
        var tableRow3 = ["雨伞;5.00;3;15.00"];
        JXPrintPlugin.addRow(tableRow1, null, errorCallback);
        JXPrintPlugin.addRow(tableRow2, null, errorCallback);
        JXPrintPlugin.addRow(tableRow3, null, errorCallback);
        //打印表格
        JXPrintPlugin.printTable(successCallback, errorCallback);
    } catch (error) {
        outputLog("Error: " + error)
    }
}
function setFont() {
    //设置字体
    try {
        var jsonstr = [0];
        JXPrintPlugin.setFont(jsonstr, successCallback, errorCallback);
    } catch (error) {
        outputLog("Error: " + error)
    }
}
function setPrinter() {
    //设置打印格式
    try {
        var jsonstr = [0];
        JXPrintPlugin.setPrinter(jsonstr, successCallback, errorCallback);
    } catch (error) {
        outputLog("Error: " + error)
    }
}
function initPrinter() {
    //初始化打印机，清除缓存
    try {
        JXPrintPlugin.initPrinter(successCallback, errorCallback);
    } catch (error) {
        outputLog("Error: " + error)
    }
}
function read() {
    //获取返回值
    try {
        var jsonstr = [0];
        JXPrintPlugin.read(jsonstr, successCallback, errorCallback);
    } catch (error) {
        outputLog("Error: " + error)
    }
}
function sendBytesData(code) {
    //发送数据
    try {
        var jsonstr = [code];
        // JXPrintPlugin.read(jsonstr, successCallback, errorCallback);
        JXPrintPlugin.sendBytesData(jsonstr, successCallback, errorCallback);
    } catch (error) {
        outputLog("Error: " + error)
    }
}



window.addEventListener('message',function(e) {
    var msg = e['data']
    outputLog('接收子页面传来的信息')
    if(!msg) return

    if( msg['type'] == 'print'){
        outputLog('收到打印请求')
        closeConnect()
        JXPrintPlugin.connectPrinter(function(){
            outputLog('打印机链接成功')
            doPrint(msg)
        }, function(error){
            outputLog('打印机链接失败:'+error)
        });
        
    }else if(msg['type'] == 'camera'){
        outputLog('收到拍照请求')
        openCamera(msg['key'])
    }else{
        // outputLog('请求类型无效：'+msg['type'])
    }
});





//打印最短间隔时间限制（毫秒）
var printIntervalTime = 4500
//上次打印结束时间（时间戳）
var lastPrintTime = null
function setLastPrintTime(){
    lastPrintTime = new Date().getTime()
}
function checkLastPrintTime(){
    if(!lastPrintTime){
        return true
    }
    var nowTime = new Date().getTime()
    var timez = nowTime - lastPrintTime
    if( timez < printIntervalTime){
        var sz = Math.round(timez/1000)
        //alert('打印间隔时间过短,请'+sz+'秒后再试')
        alert('打印间隔时间过短，请稍后再试 ')
        return false
    }
    return true
}

//打印测试
function doPrintTest(){
    var msg = {
        
        action: "postMessage",
        code: "收202107010002-2",
        info: {项目: "测试项目", 操作员: "收发料员_测试1", 供应商: "测试供应商公司"},
        list: [
            {材料名称: "玻璃钢安全帽", 规格型号: "大号", 数量: 20, 计量单位: "个"},
            {材料名称: "钢卷尺", 规格型号: "5m", 数量: 5, 计量单位: "个"},
        ],
        order: {info: ["项目", "供应商", "用料单位", "操作员"], list: ["材料名称", "规格型号", "数量", "计量单位"]},
        time: "2021-07-01 16:38:28",
        title: "收料小票",
        type: "print",
    }
    
    outputLog('收到测试打印请求')
    closeConnect()
    JXPrintPlugin.connectPrinter(function(){
        outputLog('打印机链接成功')
        doPrint(msg)
    }, function(error){
        outputLog('打印机链接失败:'+error)
    });
}

//执行打印
function doPrint(msg){


    //打印表格
    try {
        if(!checkLastPrintTime()){
            outputLog("未通过时间间隔检查，结束打印")
            return
        }
        outputLog("开始打印")
        setLastPrintTime()
        JXPrintPlugin.initPrinter(function(){
            outputLog('打印机 初始化成功')
            
            
            
            //打印标题
            var title = '           '+msg['title']
            // JXPrintPlugin.setPrinter([2,1],successCallback, errorCallback);
            
            JXPrintPlugin.setPrinter([2,0],function(){
                
                //创建表格
                var tableTitle = [";",";","9,23"];
                // var tableTitle = [";;",";","8,13,11"];
                JXPrintPlugin.createTable(tableTitle, null, errorCallback);
                
                //添加行
                var code = '编号:;'+msg['code']
                // var code = '编号:;'+msg['code']+';'
                outputLog('将info信息填入表1：\n'+code);
                JXPrintPlugin.addRow([code], null, errorCallback);
                printLine();
                
                var time = '时间:;'+msg['time']
                // var time = '时间:;'+msg['time']+';'
                outputLog('将info信息填入表1：\n'+time);
                JXPrintPlugin.addRow([time], null, errorCallback);
                printLine();

                //输出其他信息
                var dataList = msg['info']
                var list_order = msg['order']['info']
                for(var i=0;i<list_order.length;i++){
                    let key = list_order[i]
                    let value = dataList[key]
                    if(value){
                        let rowText = key+":;"+value
                        // let rowText = key+":;"+value+';'
                        outputLog('将info信息填入表1：\n'+rowText);
                        JXPrintPlugin.addRow([rowText], null, errorCallback);
                        if(i < (list_order.length)-1){
                            printLine();
                        }
                    }
                }
                
                
                
                JXPrintPlugin.printText(['\n'], successCallback, errorCallback);
                outputLog('输出title: '+title);
                JXPrintPlugin.printText([title], successCallback, errorCallback);
                JXPrintPlugin.printText(['\n'], successCallback, errorCallback);

                //打印表格
                outputLog('执行打印表1');
                JXPrintPlugin.printTable(function(){
                    outputLog('准备输出材料列表信息 表2');
                    //JXPrintPlugin.printText(['\n--------------------------------\n'], successCallback, errorCallback);
                    JXPrintPlugin.setPrinter([2,1],successCallback, errorCallback);
                    JXPrintPlugin.printText(['\n材料列表\n\n'], successCallback, errorCallback);
                    JXPrintPlugin.setPrinter([2,0],successCallback, errorCallback);

                    var dataList = msg['list']
                    // var list_order = msg['order']['list']
                
                    for(let j=0;j<dataList.length;j++){
                        var data = dataList[j]
                        
                        let unit = getCode(data['计量单位']);
                        // var text = data['材料名称']+'  '+data['规格型号']+'  '+data['数量']+''+unit
                        var text = makePrinterText_m(data['材料名称'],data['规格型号'],data['数量'],unit)
                        outputLog('将list信息填入表2：\n'+text);
                        // JXPrintPlugin.addRow([text], null, errorCallback);

                        JXPrintPlugin.printText([text], successCallback, errorCallback);
                        printLine('text');
                    }

                    outputLog('输出签名');
                    JXPrintPlugin.printText(['\n签名:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n'], successCallback, errorCallback);
                    // JXPrintPlugin.printText(['\n签名:\n\n\n\n'], successCallback, errorCallback);
                    outputLog('打印结束');
                    setLastPrintTime()
                    // closeConnect()
                }, errorCallback);
                // printLine('mTitle')

                // outputLog('材料表 初始化成功：')
                
            }, errorCallback);
            
            
            


            

        }, function(error){
            outputLog('打印机 初始化错误：'+error)
        });

    } catch (error) {
        outputLog("打印流程中出现错误 Error: " + error)
    }

}

function makePrinterText_m(clmc,ggxh,num,unit){
    let printerRowMaxLength = 30 //打印机一行最大31个字符位（一个汉字占两个位）
    let textOriginLength_clmc = getStrLengthOnPrinter(clmc)
    console.log('textOriginLength_clmc',textOriginLength_clmc)

    let otherStr = '  '+ggxh+'  '+num+unit

    let textOriginLength_all = textOriginLength_clmc+otherStr.length

    if(textOriginLength_all > printerRowMaxLength){
        //需做换行处理
        let otherStrRow1MaxLength = printerRowMaxLength - textOriginLength_clmc
        console.log('otherStrRow1MaxLength',otherStrRow1MaxLength)
        if(otherStr.length > otherStrRow1MaxLength){
            otherStrList = []
            otherStrList.push(otherStr.substr(0,otherStrRow1MaxLength))
            otherStrList.push(otherStr.substr(otherStrRow1MaxLength,otherStr.length))
            console.log('otherStrList',otherStrList)
            otherStr = otherStrList.join('\n')
        }
    }

    return clmc+otherStr
}

function getStrLengthOnPrinter(str){
    let originLength = str.length
    if(!originLength || originLength <=0) return 0
    //中文实际上占了两个字符，需换行
    let cnNum = getStrCnNum(str)
    let printerLength = originLength-cnNum+(cnNum*2)
    return printerLength
}
function getStrCnNum(str){

    re = /[\u4E00-\u9FA5]/g; //测试中文字符的正则

    var leng = str.match(re).length;  //计算中文的个数
    console.log('字符串“',str,'”的中文数量:',leng)
    return leng
}

// makePrinterText_m('猪哈哈哈哈材料','17*23*300','2222.333','m3')



function printLine(type='table'){
    if(type=='text'){
        JXPrintPlugin.printText(['\n- - - - - - - - - - - - - - - -\n'], successCallback, errorCallback);
    }else if(type=='table'){
        // JXPrintPlugin.addRow(['- - - - -;- - - - - - - - - - -'], null, errorCallback);
        JXPrintPlugin.addRow(['- - - - - - - - - - - - - - - -'], null, errorCallback);
    }else if(type=='list'){
        JXPrintPlugin.addRow(['- - - - - - - - - - - - - - - -'], null, errorCallback);
        // JXPrintPlugin.printText(['\n- - - - - - - - - - - - - - - -'],successCallback, errorCallback);
    }else if(type=='empty'){
        JXPrintPlugin.addRow(['                               '], null, errorCallback);
    }else if(type=='mTitle'){
        
        // JXPrintPlugin.addRow(['         材料列表          '], null, errorCallback);
        JXPrintPlugin.addRow([' ;  ;  '], null, errorCallback);
    }
}



function doPrint_old(msg){


    //setPaperType()
    //setDensity()
    
    
    //打印表格
    try {
        JXPrintPlugin.initPrinter(successCallback, errorCallback);
        
        //标题
        var title = msg['title']
        //console.log('msg',msg)
        
        // if(msg['type'] == 1){
        //     title = '收料小票'
        // }else if(msg['type'] == 0){
        //     title = '发料小票'
        // }

        JXPrintPlugin.setPrinter([2,1],successCallback, errorCallback);
        JXPrintPlugin.printText(['\n'+title+'\n'],successCallback, errorCallback);
        JXPrintPlugin.setPrinter([2,0],successCallback, errorCallback);
        //创建表格
        var tableTitle = [";",";","10,22"];
        JXPrintPlugin.createTable(tableTitle, null, errorCallback);
        //添加行
        JXPrintPlugin.addRow(['编号:;'+msg['code']], null, errorCallback);
        printLine();
        JXPrintPlugin.addRow(['时间:;'+msg['time']], null, errorCallback);
        printLine();
    
        var dataList = msg['list']
        var list_order = msg['list_order']
        for(let i=0;i<list_order.length;i++){
            let key = list_order[i]
            let value = dataList[key]
            if(value){
                let rowText = key+":;"+value
                outputLog(rowText);
                JXPrintPlugin.addRow([rowText], null, errorCallback);
                printLine();
            }
        }
        /*
        var tableRow1 = ["保鲜袋;10.00;1;10.00"];
        var tableRow2 = ["铁丝挂钩;5.00;2;10.00"];
        var tableRow3 = ["雨伞;5.00;3;15.00"];
        JXPrintPlugin.addRow(tableRow1, null, errorCallback);
        JXPrintPlugin.addRow(tableRow2, null, errorCallback);
        JXPrintPlugin.addRow(tableRow3, null, errorCallback);
        */
        //打印表格
        JXPrintPlugin.printTable(successCallback, errorCallback);
        //setPaperFeed();
        JXPrintPlugin.printText(['\n签名:\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n'], successCallback, errorCallback);
        // JXPrintPlugin.printText(['\n签名:\n'], successCallback, errorCallback);
    } catch (error) {
        outputLog("Error: " + error)
    }
    
    
}

function getPicType1(opiotns,onSuccess=function(){},onError=function(){}){
    // navigator.camera.getPicture(onSuccess,onError,opiotns)
}

if(typeof deviceType != "undefined" && deviceType){
    // alert('deviceType: '+deviceType)
}

function uploadImg(imgData,key=null){
    if(!imgData) return false
    
    var base64Head = 'data:image/jpeg;base64,'
    var timestamp=new Date().getTime()
    let fName = timestamp+'.jpeg'
    
    var file = dataURLtoFile(base64Head + imgData, fName)

    var form = new FormData();
    form.append("file", file); //第一个参数是后台读取的请求key值
    form.append("type", 'cordova_img'); 
    form.append("fName", fName); 

    var xhr = new XMLHttpRequest();
    var action = "http://182.254.196.41:8233/ioport/img/"; //上传服务的接口地址
    
    xhr.open("POST", action);
    xhr.send(form); //发送表单数据
    xhr.onreadystatechange = function(){
        if(xhr.readyState==4 && xhr.status==200){
            var ret = JSON.parse(xhr.responseText);
            // alert('ret: '+xhr.responseText)
            //处理返回的数据......
            if(ret && ret['code'] == '200'){
                // alert('上传成功！')
                let msg = {'type':'img','key':key,'imgName':ret['image']}
                // alert('向iframe发送通知：'+JSON.stringify(msg))
                var iFrame = document.getElementById('main_iframe')
                iFrame.contentWindow.postMessage(msg, '*');
            }
        }
    }
    


}

function uploadImgOld(imgData){

    var base64Head = 'data:image/jpeg;base64,'
    var timestamp=new Date().getTime()
    let fName = timestamp+'.jpeg'
    
    var file = dataURLtoFile(base64Head + imgData, fName)

    var input = document.createElement("input");
    input.type = "file";
    input.click();
    input.onchange = function(){
      var form = new FormData();
      form.append("type", 'cordova_img');
    //   form.append("file", file); 
    //   form.append("fName", fName); 
      
      
      var xhr = new XMLHttpRequest();
      var action = "http://182.254.196.41:8233/ioport/img/"; //上传服务的接口地址
      action = action+"?type=cordova_img&fName="+fName
      
      xhr.open("POST", action);
      xhr.send(form); //发送表单数据
      xhr.onreadystatechange = function(){
        if(xhr.readyState==4 && xhr.status==200){
          var ret = JSON.parse(xhr.responseText);
          //处理返回的数据......
          if(ret && ret['code'] == '00'){
              alert('上传成功！')
          }
        }
      }
    }
  }


function onSuccess(res){
    if(!res) return
    
    uploadImg(res)
}
function onFail(res){
    // alert('app.js onFail 2')
    // alert(JSON.stringify(res))
    outputLog('拍照失败: '+ JSON.stringify(res))
    
}



function openCamera(key){
    // alert('app.js openCamera')
    outputLog('开始拍照')
    // https://blog.csdn.net/qq_41995919/article/details/102639711
    navigator.camera.getPicture(function(res){uploadImg(res,key)}, onFail, { 
    // navigator.camera.getPicture(function(){alert('app.js onSuccess')}, function(){alert('app.js onFail')}, { 
        quality: 70, 
        destinationType: Camera.DestinationType.DATA_URL,
        encodingType: Camera.EncodingType.JPEG,
        sourceType: Camera.PictureSourceType.CAMERA,//指定图片来自拍照

        // mediaType:'PICTURE',
        
        // saveToPhotoAlbum:true
        // destinationType: Camera.DestinationType.DATA_URL, 
        // encodingType: Camera.EncodingType.JPEG, 
        // sourceType: mySourceType 
    })
}

function dataURLtoFile(dataurl, filename) {
    var arr = dataurl.split(',')
    var mime = arr[0].match(/:(.*?);/)[1]
    var bstr = window.atob(arr[1])
    var n = bstr.length
    var u8arr = new Uint8Array(n)
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n)
    }
    var blob = new Blob([u8arr], {type: mime})
    blob.lastModifiedDate = new Date()
    blob.name = filename
    return blob
}




